<template>
  <div class="api-demo">
    <el-card header="API 请求示例">
      <div class="mb-4">
        <el-button @click="handleFetchData" :loading="loading" type="primary"> 获取数据 </el-button>
        <el-button @click="handleGetStatus" :loading="loading" type="info"> 获取状态 </el-button>
        <el-button @click="showAddDialog = true" type="success"> 添加数据 </el-button>
      </div>

      <div v-if="status" class="mb-4">
        <el-tag>状态: {{ status.status }}</el-tag>
        <el-tag type="info" class="ml-2">
          更新时间: {{ new Date(status.timestamp).toLocaleString() }}
        </el-tag>
      </div>

      <el-table :data="data" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="120" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="value" label="值" />
        <el-table-column prop="timestamp" label="时间戳" width="180">
          <template #default="{ row }">
            {{ row.timestamp ? new Date(row.timestamp).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="showAddDialog" :title="editingItem ? '编辑数据' : '添加数据'" width="500px">
      <el-form :model="formData" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="值">
          <el-input v-model="formData.value" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useApi } from '@/composables/use-api';
import type { DataItem } from '@/services/api-service';
import { ElMessageBox } from 'element-plus';

const {
  loading,
  error,
  data,
  status,
  fetchData,
  postData,
  updateData,
  deleteData,
  getStatus,
  startStatusPolling
} = useApi();

const showAddDialog = ref(false);
const editingItem = ref<DataItem | null>(null);
const formData = ref({
  name: '',
  value: ''
});

const handleFetchData = async () => {
  await fetchData();
};

const handleGetStatus = async () => {
  await getStatus();
};

const handleEdit = (item: DataItem) => {
  editingItem.value = item;
  formData.value = {
    name: item.name,
    value: item.value
  };
  showAddDialog.value = true;
};

const handleSubmit = async () => {
  if (editingItem.value) {
    // 编辑
    const result = await updateData(editingItem.value.id, formData.value);
    if (result) {
      showAddDialog.value = false;
      resetForm();
    }
  } else {
    // 添加
    const result = await postData({
      ...formData.value,
      timestamp: Date.now()
    });
    if (result) {
      showAddDialog.value = false;
      resetForm();
    }
  }
};

const handleDelete = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await deleteData(id);
  } catch {
    // 用户取消删除
  }
};

const resetForm = () => {
  formData.value = {
    name: '',
    value: ''
  };
  editingItem.value = null;
};

// 组件挂载时获取数据
onMounted(() => {
  handleFetchData();
  handleGetStatus();

  // 开始状态轮询（可选）
  const stopPolling = startStatusPolling(10000); // 每10秒更新一次状态

  // 组件卸载时停止轮询（这里需要在实际使用时添加 onUnmounted 导入）
  // onUnmounted(() => {
  //   stopPolling()
  // })
});
</script>

<style scoped>
.api-demo {
  padding: 20px;
}
</style>
